<?php

/**
 * Description of MainController
 *
 * @author Kopi
 */
abstract class MainController extends Controller {

    /**
     * @var User
     */
    protected $user;
    protected $userLoggedIn;
    private static $user_objects = array('MfUser', 'Performer', 'User', 'Agency');
    protected $tables = array();

    public function AdminLoginRedirectAction($param) {
        $this->AddRedirect(Router::GenerateUrl(array('login' => 'index')), 0);
    }

    public function adminRun($param) {
        
    }

    /**
     * Dodatkowy starter kontrolera
     *
     */
    protected function Run($param = array()) {
        
        if (Config::Get('site') == PageType::ADMIN) {
            session_start();
            $this->RunShared('LeftPanel', $param);

            $this->GetRedirectInfo();
         
        } else if (Config::Get('site') == 'Lp') {
            
        } else if (Config::Get('site') == 'Shop') {
            //session_start();
            $this->RunShared('LeftPanel', $param);

            $this->GetRedirectInfo();
            $this->addScript('jquery-1.4.4.min.js', 'file', 'top', 1);
            $this->addScript('jquery-validate/jquery.validate.js', 'file', 'top', 2);
            $this->addScript('jquery-validate/localization/messages_pl.js', 'file', 'top', 3);
            //jquery.numberformatter-1.2.2.js
//			$this->addScript('jquery-ui-1.8.5.custom.min.js','file','top',2);
            //$this->addScript('Admin/jquery.controls.js', 'file', 'top', 4);
        } else {
            session_start();

            if (!SessionProxy::IsSetValue('DEFAULT_METRIC')) {
                if (Request::getClientIP()) {
                    $dalObj = CountryIpDAL::GetDalDataObj();
                    $dalObj->addCondition('ip_from_inet', "INET_ATON('" . Request::getClientIP() . "')", '<=', ' AND ');
                    $dalObj->addCondition('ip_to_inet', "INET_ATON('" . Request::getClientIP() . "')", '>=', ' AND ');
                    //var_dump($dalObj);
                    $result = CountryIpDAL::GetResult($dalObj);
                    if (isset($result[0])) {
                        $metric_system_type = $result[0]->getMetric();
                        SessionProxy::SetValue('DEFAULT_METRIC', $metric_system_type);
                    }
                } else {
                    $metric_system_type = 0;
                }
            } else {
                $metric_system_type = SessionProxy::GetValue('DEFAULT_METRIC');
            }
            Registry::Remove('METRIC_SYSTEM_TYPE');
            Registry::Set('METRIC_SYSTEM_TYPE', $metric_system_type);

            $this->smarty->assign('_menu_tab', Registry::Get('menu_tab'));

            $this->RunShared('MyList', $param);
            $this->AddBreadCrumb('tennizoom', Router::GenerateUrl('default'));

            list($this->user, $this->userLoggedIn, $message) = $this->RunModule('Auth', 'CheckUser', $param);
            $this->smarty->assign('_user', $this->user);
            $this->smarty->assign('_userLoggedIn', $this->userLoggedIn);

            Registry::Set('_user', $this->user);
            Registry::Set('_userLoggedIn', $this->userLoggedIn);

            if ($this->userLoggedIn) {
                $dalCount = UserMessagesDAL::GetDalDataObj();
                $dalCount->setCount('COUNT(id_user_messages)');
                $dalCount->addCondition('deleted_user', '0');
                $dalCount->addCondition('type', '2', '<');
                $dalCount->addCondition('readed_recipient', '0');
                //$dalCount->addCondition('(user_messages.id_user', $user->getId());
                $dalCount->addCondition('id_recipient', $this->user->getId());

                $countMessages = UserMessagesDAL::GetResult($dalCount);
                $this->smarty->assign('messagesCount', $countMessages);
            }

            if ($this->userLoggedIn) {
                $metric_system_type = $this->user->getValuesMetric();
                Registry::Remove('METRIC_SYSTEM_TYPE');
                Registry::Set('METRIC_SYSTEM_TYPE', $metric_system_type);
            }

            $this->smarty->assign('_display_metric_system_type', Registry::Get('METRIC_SYSTEM_TYPE'));

            /*
              $this->smarty->assign('_user_classes',MfUser::$available_classes);


             */


            $this->GetRedirectInfo();

            /*
              $this->addScript('jquery-1.4.2.min.js','file','top',1);
              if($this->renderer == 'normal')$this->addScript('jquery.prettyPhoto.js','file','top',2);
              if($this->renderer == 'normal')$this->addScript('jquery.validate.js','file','top',3);
              $this->addScript('jquery.swfobject.1-1-1.min.js','file','top',4);
              if($this->renderer == 'normal')$this->addScript('jquery.popover.js','file','top',5);
              $this->addScript('jquery.cookie.js','file','top',10);
              $this->addScript('jquery.md5.js','file','top',11);
              $this->addScript('AutoLoad.js','file','top',12);
              $this->addScript('translate.js','file','top',13);
              $this->addScript(URL_MAIN.'/language.js','file','top',14);
              $this->addScript('timezone.js','file','top',15);

              $this->addStyle(URL_STATIC_CONTENT.'/css/Strona/style.css');
              if($this->renderer == 'normal')$this->addStyle(URL_STATIC_CONTENT.'/css/Strona/lightbox/prettyPhoto.css');
             */
            //jquery.numberformatter-1.2.2.js
            //jshashtable-2.1.js
            $this->addScript('jquery-1.4.4.min.js', 'file', 'top', 1);
            $this->addScript('sliders.js', 'file', 'top', 2);
            $this->addScript('jshashtable-2.1.js', 'file', 'top', 3);
            $this->addScript('jquery.numberformatter-1.2.2.js', 'file', 'top', 4);


            $this->addScript('userInterface.js', 'file', 'top', 10);
            $this->addScript('translate.js', 'file', 'top', 11);
            $this->addScript('jquery.cookie.js', 'file', 'top', 12);
            $this->addStyle(URL_STATIC_CONTENT . '/css/style.css');



            $this->smarty->assign('sessionid', session_id());
            $this->smarty->assign('_uTime', Registry::Get('uTime'));
            if (Registry::Exists('__userLoginMessage')) {
                $this->runShared('InfoFrame', array('type' => 'ok', 'info' => Registry::Get('__userLoginMessage')));
            }

            if (!$this->userLoggedIn) {
                if (isset($_COOKIE['qrf_proposal']) && $_COOKIE['qrf_proposal'] == 1) {
                    $proposal = MfDictionaryDAL::RegistryTranslate('after_qrf_proposal');
                    $proposal = str_replace('__REGISTRATION_LINK__', Router::GenerateUrl('signIn'), $proposal);
                    $this->addScript("

function showProposal() {
	popUp('$proposal');
	$.cookie('qrf_proposal','0',{expires: 1});
}

window.setTimeout(showProposal,10000);

", 'code', 'top', 13);
                } elseif (isset($_COOKIE['qrf_taken'])) {
                    $qrf = $_COOKIE['qrf_taken'];
                    $date = date('Y-m-d');

                    if ($qrf != $date) {
                        $proposal = MfDictionaryDAL::RegistryTranslate('periodical_qrf_proposal');
                        $proposal = str_replace('__REGISTRATION_LINK__', Router::GenerateUrl('signIn'), $proposal);

                        $this->addScript("

function showProposal() {
	popUp('$proposal');
	$.cookie('qrf_taken','$date');
}

window.setTimeout(showProposal,3000);

", 'code', 'top', 13);
                    }
                }
            }

//			if ($this->user instanceof User && Router::$curLabel != 'accountDepositAfterRegistration' && Router::$curLabel != 'accountDeposit' && $this->user->GetStatus() == User::NOT_PAID) {
//				header("Location: " . Router::GenerateUrl("accountDepositAfterRegistration"));
//				die();
//			}
        }
	
    }

    protected function PostRun($param) {
        if (Config::Get('site') == PageType::STRONA) {
            $this->RunShared('Header', $param);
            $this->RunShared('Footer', $param);
        }
    }

    protected function Seo($class = __CLASS__, $method = __METHOD__) {


        $seoObj = WpSeoDAL::GetByType(WpSeo::GetMapByController($class . $method));
        if (isset($seoObj) && is_object($seoObj)) {
            if ($seoObj->getTitle() != '') {

                $this->AddTitle($seoObj->getTitle());
            }
            if ($seoObj->getDescription() != '') {
                $this->AddDescription($seoObj->getDescription());
            }
            if ($seoObj->getKeywords() != '') {
                $this->AddKeywords($seoObj->getKeywords());
            }
        }
    }

    public function Error404Action($param) {
        $this->addDescription('404');
        $this->addTitle('404');
        //echo '<pre>';
        //var_dump(Router::$route);
        //print '404';
        //die;
        //$this->SetAjaxRender();
        //$this->SetNoRender();
        //header("Status: 404 Not Found");
        //$this->content=file_get_contents('error.html');
        //include("error.html");
        //header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
        //$this->AddRedirect('error.html', 0);
        //$this->AddRedirect(Router::GenerateUrl(array('_value'=>'error')), 0, 301);
    }

    /**
     * informacjay o przekierowaniu
     *
     * @param string $url
     * @param string $info
     */
    protected function AddRedirectInfo($info, $type = null, $url = null, $jsRedirect = false) {
        SessionProxy::SetValue("frameInfo", $info);

        if ($type != null) {
            SessionProxy::SetValue("frameType", $type);
        }

        $_POST = array();
        if ($url != null && $jsRedirect == false)
            $this->AddRedirect($url, -1);
        else if ($url != null)
            $this->content = "document.location.href='$url';";
    }

    /**
     * PObranie informacji o przekierowaniu
     *
     */
    private function GetRedirectInfo() {
        if (SessionProxy::GetValue("frameInfo") != "") {

            $this->RunShared('InfoFrame', array('type' => SessionProxy::GetValue('frameType'), 'info' => SessionProxy::GetValue("frameInfo")));

            SessionProxy::ClearValue('frameType');
            SessionProxy::ClearValue('frameInfo');
        }
    }

    /**
     * Weryfikacja czy user jest zalogowany
     *
     * @return boolean
     */
    public function IsUser() {
        if (is_object($this->user)) {

            return true;
        } else {
            return false;
        }
    }

    protected function UserSession() {
        if ($this->user) {
            $id = $this->user->GetId();
            if (!empty($id) && (int) $id > 0) {
                ActiveChecker::Touch($id);
            }
        }
    }

    protected function RemoveUserSession() {
        if ($this->user) {
            $id = $this->user->GetId();
            if (!empty($id) && (int) $id > 0) {
                ActiveChecker::Remove($id);
            }
        }
    }

    protected function FormatAjaxOutput($errors, $param) {
        $out = array();
        $validateField = null;
        if (Request::Check('validate'))
            $validateField = Request::GetPost('validate');
        if (isset($param['redirect']) && !isset($param['field'])) {
            $out['redirect'] = $param['redirect'];
        }
        if (empty($errors)) {
            $out['success'] = true;
        } else {
            $out['fields'] = array();
            foreach ($errors as $row) {
                if (isset($param['field'])) {
                    if ($param['field'] == $row['field'] || $row['field'] == urldecode($param['field'])) {
                        $out['fields'][$param['field']] = $row;
                    } elseif ($validateField == $row['field']) {
                        $out['fields'][$validateField] = $row;
                    }
                } else {
                    $out['fields'][$row['field']] = $row;
                }
            }
            if (!empty($out['fields'])) {
                $out['success'] = false;
            } else {
                $out['success'] = true;
            }
        }
        if (isset($param['msg'])) {
            $out['msg'] = $param['msg'];
        }
        if (isset($param['hide'])) {
            $out['hide'] = $param['hide'];
        }
        return json_encode($out);
    }

    public final function GeneratePopover($title, $image, $message, $buttons, $inputText = false) {
        $this->SetAjaxRender(true);
        //$this->partialTemplate = '../Popover/PopoverSmall.tpl';
        $this->smarty->assign('popoverButtons', $buttons);
        $this->smarty->assign('popoverTitle', $title);
        $this->smarty->assign('popoverImage', $image);
        $this->smarty->assign('popoverMessage', $message);
        $this->smarty->assign('popoverInputText', $inputText);

        return $this->smarty->fetch('partial/Popover/PopoverSmall.tpl');
    }

    public function GetDictionary($keyword, $replacement = array()) {
        $dictionaryArray = Registry::Get("dictionary");
        return vsprintf($dictionaryArray[$keyword], $replacement);
    }

    private function LoadDictionary($lang = "pl") {
        Registry::Set("dictionary", MfDictionaryDAL::GetAllVariables($lang, 36000));
    }

    /*
     * tłumaczenie słownika
     */

    protected function T($label, $param = array()) {
        return Utils::Translate($label, $this->user, $param);
    }

    public static function GenerateTagCloud($tagsArray) {
        $minFontSize = 1;
        $maxFontSize = 7;
        $stepB = 1;
        $limit = 0;
        $newArray = array();

        for ($i = 0; $i < count($tagsArray); $i++) {

            $arrayObj[] = $tagsArray[$i];
            $counterValues[] = $tagsArray[$i]->GetCounter();
        }
        if (isset($arrayObj)) {

            $maxCounterValue = max(array_values($counterValues));
            $minCounterValue = min(array_values($counterValues));


            $spread = $maxCounterValue - $minCounterValue;

            if ($spread == 0) {
                $spread = 1;
            }
            $step = ($maxFontSize - $minFontSize) / $spread;



            $count = count($arrayObj);


            //$randomKeys = array_rand($arrayObj, $limit);

            for ($i = 0; $i < $count; $i++) {
                $size = round($minFontSize + (($arrayObj[$i]->GetCounter() - $minCounterValue) * $step));

                $arrayObj[$i]->SetFontSize($size);
                $newArray[] = $arrayObj[$i];
            }

            return $newArray;
        }
    }

    public function checkAccess($resource, $default = false, $user = null) {
        if (is_null($user)) {
            $user = $this->user;
        }

        if (is_null($user)) {
            return $default;
        }

        return $user->checkAccess($resource, $default);
    }

    public function RestrictedAccess($param, $role = null) {

        if (is_null($role) || (!is_string($role) && !is_array($role)))
            return false;

        if (!$this->userLoggedIn && ((is_string($role) && $role == 'guest') || (is_array($role) && in_array('guest', $role)))) {
            return false;
        }

        if ((is_object($this->user) && in_array(get_class($this->user), array_keys(MfUser::$available_classes)) && $this->user->hasRole($role))) {

            Router::CleanUrlHistory();

            $savedPost = unserialize(SessionProxy::GetValue('login_fail_saved_post'));
            $savedGet = unserialize(SessionProxy::GetValue('login_fail_saved_get'));
            $savedFile = unserialize(SessionProxy::GetValue('login_fail_saved_file'));

            SessionProxy::ClearValue('login_fail');
            SessionProxy::ClearValue('login_fail_saved_post');
            SessionProxy::ClearValue('login_fail_saved_get');
            SessionProxy::ClearValue('login_fail_saved_file');

            if (is_array($savedPost))
                foreach ($savedPost AS $k => $row)
                    $_POST[$k] = $row;
            if (is_array($savedGet))
                foreach ($savedGet AS $k => $row)
                    $_GET[$k] = $row;
            if (is_array($savedFile))
                foreach ($savedFile AS $k => $row)
                    $_FILES[$k] = $row;

            return false;
        }/* else if(in_array(get_class($this->user), self::$user_objects)){

          } */else {

            $loginFail = SessionProxy::IsSetValue('login_fail') ? SessionProxy::GetValue('login_fail') : 0;
            $loginFail++;

            if ($loginFail == 1) {
                $savedPost = serialize(Request::GetAllPost(false));
                $savedGet = serialize(Request::GetAllGet(false));
                $savedFile = serialize($_FILES);

                SessionProxy::SetValue('login_fail_saved_post', $savedPost);
                SessionProxy::SetValue('login_fail_saved_get', $savedGet);
                SessionProxy::SetValue('login_fail_saved_file', $savedFile);
            }

            Router::SaveUrl($param);

            $url = isset($param['redirectUrlForRestrictedAccess']) ? $param['redirectUrlForRestrictedAccess'] : Router::GenerateUrl('redirectMainSite', array());

            if ($this->renderer == 'ajax') {
                $this->content = "document.location.href='$url'";
            } else {
                $msg = Registry::Exists('authMsg') ? Registry::Get('authMsg') : $this->t('Nie posiadasz uprawnień do oglądania tej strony');
                $this->AddRedirectInfo($msg, 'ok', $url, 0);
            }


            return true;
        };
    }

    protected function sortTables($param) {

        $this->tables = SessionProxy::IsSetValue('__sort_table_394rufh__') ? unserialize(SessionProxy::GetValue('__sort_table_394rufh__')) : array();


        if (isset($param['tid'])) {
            $saved_table_data = $this->getTableData($param['tid'], $param);

            $table_data = array(
                'o' => isset($param['o']) ? $param['o'] : (isset($saved_table_data['o']) ? $saved_table_data['o'] : null),
                'v' => isset($param['v']) ? $param['v'] : (isset($saved_table_data['v']) ? $saved_table_data['v'] : null),
//				'p' => isset($param['p'])?$param['p']:(isset($saved_table_data['p'])?$saved_table_data['p']:null),
                't' => isset($param['t']) ? $param['t'] : (isset($saved_table_data['t']) ? $saved_table_data['t'] : null)
            );


            $this->tables[$param['tid']] = $table_data;
        }

        SessionProxy::SetValue('__sort_table_394rufh__', serialize($this->tables));
    }

    protected function getTableData($tid, $param, $defaults = array()) {
        $table_data = array();
        if (isset($this->tables[$tid])) {
            $table_data = array(
                'o' => isset($this->tables[$tid]['o']) ? $this->tables[$tid]['o'] : (isset($defaults['o']) ? $defaults['o'] : null),
                'v' => isset($this->tables[$tid]['v']) ? $this->tables[$tid]['v'] : (isset($defaults['v']) ? $defaults['v'] : null),
//				'p' => isset($this->tables[$tid]['p'])?$this->tables[$tid]['p']:(isset($defaults['p'])?$defaults['p']:null),
                't' => isset($this->tables[$tid]['t']) ? $this->tables[$tid]['t'] : (isset($defaults['t']) ? $defaults['t'] : null)
            );
            $this->tables[$tid] = $table_data;
        } else {
            $table_data = array(
                'o' => (isset($param['o']) ? $param['o'] : (isset($defaults['o']) ? $defaults['o'] : null)),
                'v' => (isset($param['v']) ? $param['v'] : (isset($defaults['v']) ? $defaults['v'] : null)),
                't' => (isset($param['t']) ? $param['t'] : (isset($defaults['t']) ? $defaults['t'] : null)),
//				'v' => (isset($defaults['v'])?$defaults['v']:(isset($param['v'])?$param['v']:null)),
//				'p' => (isset($defaults['p'])?$defaults['p']:null),
//				't' => (isset($defaults['t'])?$defaults['t']:(isset($param['t'])?$param['t']:null))
            );
            $this->tables[$tid] = $table_data;
        }
        $this->smarty->assign('table_data', $this->tables);
        $this->smarty->assign('param_from_url', $param);

        return $table_data;
    }

    public function configTables($param) {

        if (is_array($this->tableConfig))
            foreach ($this->tableConfig AS $table_name => $params) {
                if (isset($param['tid']) && $table_name !== $param['tid']) {
                    $table_data = $this->getTableData($table_name, array(), array('o' => $params['o']['_'], 'v' => $params['v'], 't' => $params['t']));
                    $table_data['v'] = in_array($table_data['v'], array('malejaco', 'd')) ? 'DESC' : 'ASC';
                    $table_data['o'] = $params['o'][$table_data['o']];
                    $table_data['p'] = 1;
                    $this->tableParams[$table_name] = $table_data;
                    continue;
                }
                // dane do tabelek i paginacji start - product_table
                $table_data = $this->getTableData($table_name, $param, array('o' => $params['o']['_'], 'v' => $params['v'], 't' => $params['t']));
                $table_data = array_merge($table_data, $param);
                $table_data['v'] = in_array($table_data['v'], array('malejaco', 'd')) ? 'DESC' : 'ASC';
                $table_data['o'] = $params['o'][$table_data['o']];
                if (isset($param['page']))
                    $param['strona'] = $param['page'];
                $table_data['p'] = isset($param['strona']) ? $param['strona'] : 1;
                $this->tableParams[$table_name] = $table_data;
                //dane do tabelek i paginacji koniec - product_table
            }
    }

    //do jakiegoś tam admina starego - ależ mnie to denerwuje
    public function AjaxRemoveAction($param) {
        $this->setAjaxRender();

        try {
            $data = Request::GetAllPost();

            if (isset($data['ids']) && is_array($data['ids']) && !empty($data['ids'])) {
                $dalData = call_user_func(array($this->GetMainClassName() . 'DAL', 'GetDalDataObj'));

                $dalData->addCondition(call_user_func(array($this->GetMainClassName() . 'DAL', 'GetObjClassTablePK')), '(' . implode(',', $data['ids']) . ')', 'IN');
                $adminList = call_user_func(array($this->GetMainClassName() . 'DAL', 'GetResult'), $dalData);


                foreach ($adminList AS $adminObj) {
                    call_user_func(array($this->GetMainClassName() . 'DAL', 'Delete'), $adminObj->getDalDataObj());
                }
            }
            $this->content = json_encode(true);
        } catch (Exception $e) {
            $this->content = json_encode($e->GetMessage());
        }
    }

    protected function GetList($class, $tableData, $oTable, $vTable, $default = true) {
        $table_data = $this->getTableData($tableData[0], $tableData[1], $tableData[2]);
        //'dictionary_table', $param, array('o' => 'nazwa', 'v' => 'malejaco', 't' => 10));

        if (isset($vTable[$table_data['v']])) {
            $v = $vTable[$table_data['v']];
        } else {
            $k = array_keys($vTable);
            $v = $vTable[$k[0]];
        }

        $o = $oTable[$table_data['o']];
        $p = isset($tableData[1]['strona']) ? $tableData[1]['strona'] : 1;

        $dalData = call_user_func(array($class . "DAL", 'GetDalDataObj'));
        $dalData->SetCount(true);
        $this->smarty->assign('c', call_user_func(array($class . "DAL", 'GetResult'), $dalData));
        //dane do tabelek i paginacji koniec - users_table
        $dalData->setCount(false);
        $dalData->setSortBy("$o $v");
        $dalData->SetLimit((($p - 1) * $table_data['t']) . ', ' . $table_data['t']);

        if ($default == true) {
            $this->smarty->assign('table_type', $tableData[0]);
        }

        return call_user_func(array($class . "DAL", 'GetResult'), $dalData);
    }

}

?>
